package cn.imvc.app.models;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Resource;
import cn.imvc.app.entities.Role;
import cn.imvc.app.repositories.ResourceRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;

@Service
public class ResourceModelImpl implements ResourceModel {

	@Autowired
	ResourceRepository resourceRepository;
	public List<Resource> findResources() {
		return (List<Resource>) resourceRepository.findAll();
	}
	public Page<Resource> find(ViewRequest viewRequest) {
		return resourceRepository.findAll(ModelUtil.OrderByIdDesc(viewRequest));
	}
	public Resource get(int id) {
		return resourceRepository.findOne(id);
	}
	public Resource save( Resource resource) {
		return resourceRepository.saveAndFlush(resource);
	}
	public Resource update(int id, Resource resource) {
		Resource loadResource=get(id);
		BeanUtils.copyProperties(resource, loadResource, new String[]{"id"});
		return resourceRepository.saveAndFlush(loadResource);
	}
	
	public void delete(int id) {
		resourceRepository.delete(id);
	}
	public void deleteBatch(int[] ids) {
		for (int id : ids) {
			delete(id);
		}
		
	}
	
	public LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> getRequestMap() {
		LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap= new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
		for (Resource resource : this.findResources()) {
			Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
			for (Object object : resource.getRole()) {
				Role role = (Role) object;
				ConfigAttribute configAttribute = new SecurityConfig(
						role.getCode());
				configAttributes.add(configAttribute);
			}
			AntPathRequestMatcher requestMatcher;
			if(resource.getHttpmethod().equals("")){
				requestMatcher = new AntPathRequestMatcher(resource.getPattern());
			}else{
				requestMatcher = new AntPathRequestMatcher(
						resource.getPattern(), resource.getHttpmethod());
			}
			requestMap.put(requestMatcher, configAttributes);
		}
		return requestMap;
	}

}
